//
//  CrossMidCell.swift
//  DSP
//
//  Created by tucici on 2024/5/16.
//

import UIKit
import TCCKit

private enum ControlStatus{
    case normal
    case selected
    case disable
}
class midCellModify{
    var title:String = ""
    var ch:ChannelModel!
    init(title: String, ch: ChannelModel) {
        self.title = title
        self.ch = ch
    }
}

protocol CrossMidCellDelegate{
    func select(modify:midCellModify)
}
let updateMidCell = "updateMidCell"
class CrossMidCell: UITableViewCell {
    @IBOutlet var lowpass: UIButton!///200
    @IBOutlet var hanning: UIButton!///201
    @IBOutlet var bypass: UIButton!///202
    @IBOutlet var reset: UIButton!///203
    @IBOutlet var dB6: UIButton!///204
    @IBOutlet var dB12: UIButton!///205
    @IBOutlet var dB24: UIButton!///206
    @IBOutlet var dB36: UIButton!///207
    @IBOutlet var dB48: UIButton!///208
    @IBOutlet var sub: UIButton!///209
    @IBOutlet var add: UIButton!///210
    @IBOutlet var input: UITextField!
    private var slider : DSlider!
    private var pop : CrossPopView!
    private var btn_arr = [UIButton]()
    private var isEdit : Bool = false
    var delegate : CrossMidCellDelegate?
    override func awakeFromNib() {
        super.awakeFromNib()
        initUI()
    }
    
    func initUI(){
        backgroundColor = .clear
        btn_arr = [dB6,dB12,dB24,dB36,dB48]
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(actionForTap))
        tap.cancelsTouchesInView = false
        contentView.addGestureRecognizer(tap)
        
        let long = UILongPressGestureRecognizer(target: self, action: #selector(actionForlongPress))
        long.minimumPressDuration = 2
        reset.addGestureRecognizer(long)
        
        slider = DSlider()
        slider.delegate = self
        slider.minValue = 20
        slider.maxValue = 20000
        slider.thumImg.image = UIImage(named: "slider_p")
        slider.setColors([HEX_RED.color(), HEX_RED.color()])
        
        pop = CrossPopView()
        pop.block = {[weak self] type in
            self?.hanning.isSelected = false
            self?.hanning.setTitle(type.value, for: .normal)
            (self?.modify.title ?? "" == "High Pass" ? self?.modify.ch.highPass : self?.modify.ch.lowPass)!.type = type
            self?.delegate?.select(modify: (self?.modify)!)
            NotifyTool.post(updateChartStatus)
        }
        contentView.addSubview(slider)
        contentView.addSubview(pop)
        
        slider.snp.makeConstraints { make in
            make.height.equalTo(30.k_h)
            make.left.right.equalToSuperview().inset(30.k_w)
            make.bottom.equalToSuperview().inset(0)
        }
        
        pop.snp.makeConstraints { make in
            make.top.equalTo(hanning.snp.bottom)
            make.left.right.equalTo(hanning)
        }
    }
    
    var modify : midCellModify!{
        didSet{
            if modify.ch.select{
                NotifyTool.add(self, #selector(updateMidCellAction), updateMidCell)
            }else{
                NotifyTool.remove(self)
            }
            updateUI()
        }
    }
    
    
    
    func updateUI(){
        pop.reset()
        lowpass.setTitle(modify.title, for: .normal)
        let filter : FilterModule! = modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass
        
        hanning.isSelected = false
        hanning.setTitle(filter.type.value, for: .normal)
        pop.array = FilterType.arr_type
        input.text = "\(Int(filter.cutFrency))"
        _ = btn_arr.map{
            $0.isSelected = "\(Int(filter.slope))" == $0.currentTitle ?? ""
        }
        
        if isEdit == false {
            if modify.title == "High Pass" &&  modify.ch.highPass.bypass{
                slider.currentValue = CGFloat(20)
                input.text = "\(20)"
            }else if modify.title == "Low Pass" && modify.ch.lowPass.bypass{
                slider.currentValue = CGFloat(20000)
                input.text = "\(20000)"
            }else{
                slider.currentValue = CGFloat(filter.cutFrency)
            }
        }
        
        switch (filter.select, filter.bypass) {
        case (false, false):
            btnStatus(lowpass,.normal)
            btnStatus(hanning,.disable)
            btnStatus(bypass,.disable)
            btnStatus(reset,.disable)
            
            btnStatus(sub, .disable, 0)
            btnStatus(add, .disable, 0)
            for btn in btn_arr{
                btnStatus(btn, .disable, 0)
            }
            
            slider.enable = false
            input.isUserInteractionEnabled = false
            input.borderHexColor = HEX_BORDER_DISABLE
            input.textHexColor = HEX_TEXT_DISABLE
            
        case (_, true):
            btnStatus(lowpass,.normal)
            btnStatus(hanning,.disable)
            btnStatus(bypass,.selected)
            btnStatus(reset,.normal)
            
            btnStatus(sub, .disable, 0)
            btnStatus(add, .disable, 0)
            for btn in btn_arr{
                btnStatus(btn, .disable, 0)
            }
            
            slider.enable = false
            input.isUserInteractionEnabled = false
            input.borderHexColor = HEX_BORDER_DISABLE
            input.textHexColor = HEX_TEXT_DISABLE
        case (true, false):
            btnStatus(lowpass,.selected)
            btnStatus(hanning,.normal)
            btnStatus(bypass,.normal)
            btnStatus(reset,.normal)
            
            btnStatus(sub, .normal, 0)
            btnStatus(add, .normal, 0)
            for btn in btn_arr{
                let status : ControlStatus = "\(Int(filter.slope))" == btn.currentTitle ?? "" ? .selected : .normal
                btnStatus(btn, status, 0)
            }
            
            slider.enable = true
            input.isUserInteractionEnabled = true
            input.borderHexColor = HEX_BLACK
            input.textHexColor = HEX_BLACK
        }
    }
    
    ////处理按钮一系列状态
    private func btnStatus(_ sender:UIButton, _ status:ControlStatus, _ borderW:CGFloat=1){
        let isdB = btn_arr.contains(sender)
        sender.borderWidth = borderW
        switch status{
        case .normal:
            sender.borderHexColor = HEX_BLACK
            sender.bgHexColor = HEX_BG
            sender.textHexColor = HEX_BLACK
            sender.isEnabled = true
        case .selected:
            sender.borderHexColor = HEX_BLACK
            sender.bgHexColor = isdB ? HEX_BG : HEX_RED
            sender.textHexColor = isdB ? HEX_RED : HEX_BLACK
            sender.isEnabled = true
        case .disable:
            sender.borderHexColor = HEX_BORDER_DISABLE
            sender.bgHexColor = isdB ? HEX_BG : HEX_BG_DISABLE
            sender.textHexColor = HEX_TEXT_DISABLE
            sender.isEnabled = false
        }
    }
    
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        print("=====点击按钮tag = \(sender.tag)")
        switch sender{
        case lowpass:
            modify.ch.highPass.select = modify.title == "High Pass"
            modify.ch.lowPass.select = !modify.ch.highPass.select
            if modify.title == "High Pass"{
                modify.ch.highPass.bypass = false
            }else if modify.title == "Low Pass"{
                modify.ch.lowPass.bypass = false
            }
        case hanning:
            hanning.isSelected = !hanning.isSelected
            pop.show(hanning.isSelected)
            return
        case bypass:
            if modify.title == "High Pass"{
                modify.ch.highPass.bypass = !modify.ch.highPass.bypass
                modify.ch.highPass.select = !modify.ch.highPass.bypass
            }else if modify.title == "Low Pass"{
                modify.ch.lowPass.bypass = !modify.ch.lowPass.bypass
                modify.ch.lowPass.select = !modify.ch.lowPass.bypass
            }
        case reset:
            if modify.title == "High Pass"{
                modify.ch.highPass.cutFrency = 20
                modify.ch.highPass.slope = 6
            }else{
                modify.ch.lowPass.cutFrency = 20000
                modify.ch.lowPass.slope = 6
            }
            // filter.type = .allPass
            _ = BLEData.resetPass(modify.ch).write()
        case dB6:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).slope = 6
        case dB12:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).slope = 12
        case dB24:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).slope = 24
        case dB36:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).slope = 36
        case dB48:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).slope = 48
        case sub:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).cutFrency = max(20, (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).cutFrency - 1)
        case add:
            (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).cutFrency = min(20000, (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).cutFrency + 1)
        default:
            break
        }
        delegate?.select(modify:modify)
        NotifyTool.post(updateMidCell)
        NotifyTool.post(updateChartStatus)
    }
    
    @objc func updateMidCellAction(){
        if modify.ch.select == false{return}
        updateUI()
    }
    
    /// 点击空白处隐藏键盘
    @objc func actionForTap(_ sender: UITapGestureRecognizer){
        let location = sender.location(in:contentView)
        if pop.frame.contains(location) {return}
        if hanning.frame.contains(location){return}
        hanning.isSelected = false
        currentVC().view.endEditing(true)
        pop.show(false)
    }
    
    
    @objc func actionForlongPress(_ sender:UILongPressGestureRecognizer){
        if sender.state == .began{
            CLHUD("Reset successfully",type: .info, callBack: nil)
            actionForBtn(reset)
            let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
            feedbackGenerator.impactOccurred()
        }
    }
    
    ///cutfrency 更新，要做的一些列更新。
    private func change(_ value:Int, _ updateChar:Bool=true){
        ///更新当前cell的视图
        (modify.title == "High Pass" ? modify.ch.highPass : modify.ch.lowPass).cutFrency = value
        ///如果group选中，通知group中的另一个通道，更新
        NotifyTool.post(updateMidCell)
        if updateChar{
            ///通过delegate ，让crossviewcontroller更新折线图
            NotifyTool.post(updateChartStatus)
            delegate?.select(modify: modify)
        }
    }
    
}

//MARK: - DSliderDelgate
extension CrossMidCell : DSliderDelgate{
    func valueForChange(_ sender: DSlider) {
        isEdit = true
        change(Int(sender.currentValue),false)
    }
    func valueForChangeEnd(_ sender: DSlider) {
        isEdit = false
        change(Int(sender.currentValue))
    }
    func actionForInterval(_ sender: DSlider, _ time: Double) {
        delegate?.select(modify: modify)
        //        NotifyTool.post(updateChartStatus)
    }
}


//MARK: - UITextFieldDelegate
extension CrossMidCell:UITextFieldDelegate{
    func textFieldDidEndEditing(_ textField: UITextField) {
        if "\(textField.text ?? "0")".floatValut() < 20{
            textField.text = "20"
        }else if "\(textField.text ?? "0")".floatValut() > 20000{
            textField.text = "20000"
        }
        change(Int(textField.text ?? "0") ?? 0)
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if textField.markedTextRange != nil{return}
        change(Int(textField.text ?? "0") ?? 0)
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text ?? ""
        let result = (text+string).intValue()
        if string == "" { return true }
        else if string.isNumber() == false  {return false}
        else if result > 20000 {
            textField.text = "20000"
            return false}
        else if result < 0{
            textField.text = "20"
            return false
        }
        return true
    }
}
